package friendService

import (
	"chart.zozoo.net/app/models"
	"chart.zozoo.net/app/service/userService"
	"chart.zozoo.net/core/mysql"
	"errors"
	"fmt"
	"gorm.io/gorm"
)

// ApplyHandleParams 处理好友申请参数
type ApplyHandleParams struct {
	Uuid       string `json:"uuid"`
	FriendUuid string `json:"friend_uuid"`
	Status     int    `json:"status"`
}

// ApplyHandle 处理好友申请
func ApplyHandle(params *ApplyHandleParams) (err error) {

	friendUuid := params.FriendUuid
	uuid := params.Uuid

	//容错
	if friendUuid == uuid {
		return errors.New("不能添加自己为好友")
	}

	//获取用户信息
	myUserInfo, err := userService.InfoByUuid(uuid)
	if err != nil {
		return err
	}

	//好友的用户信息
	friendUserInfo, err := userService.InfoByUuid(friendUuid)
	if err != nil {
		return err
	}

	//获取申请记录
	applyInfo := new(models.UserFriendsApply)
	row := mysql.MysqlClient.
		Select("id", "status").
		Where("uid=? and fid=? ", friendUserInfo.Id, myUserInfo.Id).
		Find(applyInfo)
	if row.Error != nil {
		if errors.Is(row.Error, gorm.ErrRecordNotFound) {
			return errors.New("当前用户不存在申请记录")
		}

		return row.Error
	}
	//判断当前请求是否被处理
	if applyInfo.Status != 0 {
		return errors.New("当前申请记录已被处理，无需重复操作")
	}

	fmt.Println(applyInfo)

	//开启事务
	transition := mysql.MysqlClient.Begin()

	//修改申请记录状态
	res := transition.Model(applyInfo).
		Updates(map[string]interface{}{"status": params.Status})
	if res.Error != nil {
		transition.Rollback()
		return res.Error
	}

	fmt.Println("状态修改成功")
	switch params.Status {
	case 1: //同意申请
		//添加好友记录
		err = addFriend(myUserInfo.Id, friendUserInfo.Id)
		if err != nil {
			transition.Rollback()
			return err
		}
	case 2: //拒绝申请
	default:
		return errors.New("参数错误")
	}

	res = transition.Commit()
	if res.Error != nil {
		return res.Error
	}

	return nil
}
